package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.entity.ColumnData;
import cn.xuewenbao.edu.entity.Comment;
import cn.xuewenbao.edu.entity.vo.CommentVo;
import cn.xuewenbao.edu.entity.vo.MyCommentVo;
import cn.xuewenbao.edu.entity.vo.MyFavoriteVo;
import cn.xuewenbao.edu.entity.vo.MyLikeOrFavoriteContentVo;
import cn.xuewenbao.edu.mapper.CommentMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.eduorder.entity.Eduorder;
import cn.xuewenbao.ucenter.entity.vo.MemberInfoVo;
import cn.xuewenbao.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-03-26
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ColumnTypeService columnTypeService;
    @Autowired
    private ColumnDataService columnDataService;
    @Autowired
    private FavoriteService favoriteService;
    @Autowired
    private LikeContentService likeContentService;
    @Autowired
    private MemberService memberService;


    @Override
    public boolean saveComment(Comment comment) {
        int res=baseMapper.insert(comment);
        return res>0;
    }

    @Override
    public List<CommentVo> getComment(String contentId, String columnType) {
        QueryWrapper<CommentVo> wrapper=new QueryWrapper<>();
        wrapper.eq("contentId",contentId).eq("columnType",columnType).orderByAsc("gmt_create");
        return commentMapper.getCommentList(contentId, columnType);
    }

    @Override
    public Long getCommentCount(String contentId, String columnType) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("contentId", contentId).eq("columnType", columnType);
        int count = baseMapper.selectCount(wrapper);
        return (long)count;
    }

    //得到该作者的昨天的评论量
    @Override
    public Result<Map<String, Long>> getLastCommentCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到前一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String lastDay = formatter.format(calendar.getTime());
        String start = "2021-01-01 00:00:00";
        String end = lastDay + " 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        try {
            wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
            wrapper.eq("authorId", userId);
        } catch (ParseException e) {
            log.error(e.toString());
        }
        Map<String, Long> map = new HashMap<>();
        map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        result.setResult(map);
        return result;
    }

    //得到该作者的一周的评论量
    @Override
    public Result<Map<String, Long>> getWeekCommentCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1; i <= 7; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start = "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("authorId", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    //得到该作者的一月的评论量
    @Override
    public Result<Map<String, Long>> getMonthCommentCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1; i <= 30; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start =  "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("authorId", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    //删除评论（只能作者删除）
    @Override
    public Result<?> deleteComment(String userId, String commentId) {
        Result<?> result = new Result<>();
        Comment comment = baseMapper.selectById(commentId);
        if (comment.getAuthorId().equals(userId)){
            //递归删除
            deleteCommentById(commentId);
            result.setSuccess(true);
            result.setMessage("删除成功");
            return result;
        }else {
            result.setSuccess(false);
            result.setMessage("无权限删除");
            return result;
        }
    }

    @Override
    public Result<?> getMyCommentList(String userId, String columnType) {
        List<MyCommentVo> voList = new ArrayList<>();
        //获取用户在专栏下所有已支付的订单记录
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId).eq("columnType", columnType);
        List<Comment> commentList = baseMapper.selectList(wrapper);
        //根据每一条已支付的订单记录, 获取更全的vo信息
        for (Comment comment : commentList) {
            //获取 MyCommentVo contentId userId columnType
            MyCommentVo vo = new MyCommentVo();
            BeanUtils.copyProperties(comment, vo);
            vo.setCommentContent(comment.getContent());
            vo.setColumnType(columnType);
            //获取 MyFavoriteVo的 title cover viewCount
            String tableName = columnTypeService.getColumnTypeById(columnType);
            if (tableName == null) {
                return Result.error("订单的专栏类型columnType不正确");
            }
            MyLikeOrFavoriteContentVo contentVo = columnTypeService.selectMyLikeOrFavoriteContent(comment.getContentId(), tableName);
            if (contentVo == null) {    //已支付订单记录的原内容查找不到 (已删除)
                continue;   //查找下一个订单记录
            }
            BeanUtils.copyProperties(contentVo, vo);    //soure不能为 null
            //获取 MyFavoriteVo的 likeCount favoriteCount commentCount;
            QueryWrapper<ColumnData> columnDataWrapper = new QueryWrapper<>();
            columnDataWrapper.eq("content_id", comment.getContentId()).eq("column_type", columnType);
            ColumnData data = columnDataService.getOne(columnDataWrapper);
            if (data == null) { //根据订单记录, 原内容的数据查找不到 (已删除)
                continue;   //查找下一个订单记录
            }
            BeanUtils.copyProperties(data, vo);
            //获取 MyFavoriteVo的 commentCount isLike isFavorite;
            Long count = this.getCommentCount(comment.getContentId(), columnType);
            vo.setCommentCount(count);
            boolean isFavorite = favoriteService.hasFavoriteOne(userId, comment.getContentId(), columnType).isSuccess();
            vo.setIsFavorite(isFavorite);
            boolean isLike = likeContentService.hasLikeOne(userId, comment.getContentId(), columnType).isSuccess();
            vo.setIsLike(isLike);
            //获取评论的username, avatar, targetUsername, targetAvatar
            MemberInfoVo memberInfo = memberService.getMemberInfo(userId);
            if (memberInfo != null) {
                vo.setUsername(memberInfo.getUsername());
                vo.setAvatar(memberInfo.getAvatar());
            }
            MemberInfoVo targetMemberInfo = memberService.getMemberInfo(comment.getTargetUserId());
            if (targetMemberInfo != null) {
                vo.setTargetUsername(targetMemberInfo.getUsername());
                vo.setTargetAvatar(targetMemberInfo.getAvatar());
            }
            voList.add(vo);
        }
        return Result.OK("获取我的评论列表成功！", voList);
    }

    public void deleteCommentById(String id){
        baseMapper.deleteById(id);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("parentCommentId",id);
        List<Comment> comments = baseMapper.selectList(wrapper);
        for (Comment comment : comments) {
            deleteCommentById(comment.getCommentId());
        }
    }
}